package com.zz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.common.R;
import com.zz.dto.ClubAuditingDto;
import com.zz.entity.Club;
import com.zz.entity.ClubAuditing;
import com.zz.entity.SystemNotice;
import com.zz.entity.User;
import com.zz.mapper.ClubAuditingMapper;
import com.zz.mapper.ClubMapper;
import com.zz.mapper.SystemNoticeMapper;
import com.zz.mapper.UserMapper;
import com.zz.service.ClubAuditingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * 社团审核
 * @author HUAWEI
 */
@Service
public class ClubAuditingServiceImpl extends ServiceImpl<ClubAuditingMapper, ClubAuditing> implements ClubAuditingService {

    @Autowired
    private ClubAuditingMapper clubAuditingMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClubMapper clubMapper;

    @Autowired
    private SystemNoticeMapper systemNoticeMapper;

    /**
    * 分页展示所有 社团加入申请
     * 朱彦燕
    * */
    @Override
    public R<Page> page(int page, int pageSize, HttpServletRequest request){
        // 分页查询器
        Page<ClubAuditing> pageInfo = new Page<>(page, pageSize);
        Page<ClubAuditingDto> clubAuditingDtoPage = new Page<>(page, pageSize);

        // 获取活动id
        int clubId = (int) request.getSession().getAttribute("club");
        // 条件查询器
        LambdaQueryWrapper<ClubAuditing> wrapper = new LambdaQueryWrapper<>();
        // 筛选未被审核的活动
        wrapper.eq(ClubAuditing::getClubId, clubId).eq(ClubAuditing::getStatus, 0);

        // 执行分页查询
        // 在page方法内部会将查好的数据封装，赋好值给pageInfo
        clubAuditingMapper.selectPage(pageInfo, wrapper);

        // 对象拷贝(除了records,records其实就是页面中一整行一整行数据)
        BeanUtils.copyProperties(pageInfo,clubAuditingDtoPage,"records");

        List<ClubAuditing> records = pageInfo.getRecords();
        // 遍历list集合对象,item即为获取到的一个个ClubAuditing对象
        List<ClubAuditingDto> list = records.stream().map((item) -> {
            ClubAuditingDto clubAuditingDto = new ClubAuditingDto();
            // 将其ClubAuditing中的数据复制给ClubAuditingDto
            BeanUtils.copyProperties(item,clubAuditingDto);

            // 获取用户学号
            int userId = item.getUserId();

            User user = userMapper.selectById(userId);
            Club club = clubMapper.selectById(clubId);

            if (club != null){
                clubAuditingDto.setClubName(club.getName());
            }
            if (user != null){
                clubAuditingDto.setUserName(user.getName());
            }

            return clubAuditingDto;
        }).collect(Collectors.toList());// 把以上创建的dto对象都收集起来

        clubAuditingDtoPage.setRecords(list);

        return R.success(clubAuditingDtoPage);
    }

    /**
     * 同意加入社团（leader）
     * @param id
     * @return
     */
    @Override
    public R<String> agreeJoin(int id) {
        // 条件查询器
        LambdaQueryWrapper<ClubAuditing> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClubAuditing::getId, id);
        ClubAuditing clubAuditing = clubAuditingMapper.selectOne(wrapper);
        // 将审核状态码改为1， operate改为1
        clubAuditing.setStatus(1);
        clubAuditing.setOperate(1);

        clubAuditingMapper.updateById(clubAuditing);
        // 查询用户
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId, clubAuditing.getUserId());
        User user = userMapper.selectOne(userWrapper);

        // 获取社团编码
        int clubId = clubAuditing.getClubId();
        // 增加社团编码

        if (user.getClubId1() == null || user.getClubId1() == 0){
            user.setClubId1(clubId);
        }else if (user.getClubId2() == null || user.getClubId2() == 0){
            user.setClubId2(clubId);
        }else{
            user.setClubId3(clubId);
        }

        //更新数据库
        userMapper.updateById(user);

        // 将社团人数+1
        Club club = clubMapper.selectById(clubId);
        Integer people = club.getPeople();

        club.setPeople(people+1);
        clubMapper.updateById(club);

        // 设置系统通知信息
        SystemNotice systemNotice = new SystemNotice();
        systemNotice.setUserId(user.getId());
        systemNotice.setTitle("您收到一条来自社团的通知！");
        systemNotice.setInfo(user.getName()+"同学你好！恭喜你成功加入社团："+club.getName() + "!");
        systemNotice.setTime(new Date(System.currentTimeMillis()));

        systemNoticeMapper.insert(systemNotice);

        return R.success("同意加入社团！");
    }

    /**
     * 不同意加入社团（leader）
     * @param id
     * @return
     */
    @Override
    public R<String> notAgreeJoin(int id) {
        // 条件查询器
        LambdaQueryWrapper<ClubAuditing> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClubAuditing::getId, id);
        ClubAuditing clubAuditing = clubAuditingMapper.selectOne(wrapper);
        // 将审核状态码改为1， operate改为0
        clubAuditing.setStatus(1);
        clubAuditing.setOperate(0);

        clubAuditingMapper.updateById(clubAuditing);

        // 设置系统通知信息
        Club club = clubMapper.selectById(clubAuditing.getClubId());
        User user = userMapper.selectById(clubAuditing.getUserId());
        SystemNotice systemNotice = new SystemNotice();
        systemNotice.setUserId(user.getId());
        systemNotice.setTitle("您收到一条来自社团的通知！");
        systemNotice.setInfo(user.getName()+"同学你好！很遗憾！你没能加入社团："+club.getName() + "!");
        systemNotice.setTime(new Date(System.currentTimeMillis()));

        systemNoticeMapper.insert(systemNotice);

        return R.success("不同意加入社团！");
    }
}
